package util

import (
	"context"
	"gin-epg/internal/app/leveldb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

const (
	ThirdPartTokenPrefixKey = "thirdparttoken:"
	defaultExpirationTime   = 1209600 // 2 weeks in seconds
)

type ThirdPartyTokenOperator struct {
	expirationTimeInSecond int64
	client                 leveldb.LevelDBServiceClient
}

func NewThirdPartyTokenOperator(addr string, expirationTimeInSecond ...int64) (*ThirdPartyTokenOperator, error) {
	conn, err := grpc.Dial(addr, grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	expiration := defaultExpirationTime
	if len(expirationTimeInSecond) > 0 {
		expiration = int(expirationTimeInSecond[0])
	}
	client := leveldb.NewLevelDBServiceClient(conn)
	return &ThirdPartyTokenOperator{
		expirationTimeInSecond: int64(expiration),
		client:                 client,
	}, nil
}

// deleteThirdPartyToken 删除第三方 token
func (r *ThirdPartyTokenOperator) DeleteThirdPartyToken(token string) error {
	key := ThirdPartTokenPrefixKey + token
	_, err := r.client.Delete(context.Background(), &leveldb.DeleteRequest{Key: key})
	return err
}

// GetThirdPartyTokenValue 根据 token 获取值
func (r *ThirdPartyTokenOperator) GetThirdPartyTokenValue(token string) (string, error) {
	key := ThirdPartTokenPrefixKey + token
	resp, err := r.client.Get(context.Background(), &leveldb.GetRequest{Key: key})
	if err != nil {
		if status.Code(err) == codes.NotFound {
			return "", nil
		}
		return "", err
	}
	return resp.Value, nil
}

// StoreKeyValue 存储键值对
func (r *ThirdPartyTokenOperator) StoreKeyValue(token string, value string) error {
	key := ThirdPartTokenPrefixKey + token
	_, err := r.client.Put(context.Background(), &leveldb.PutRequest{Key: key, Value: value, Ttl: r.expirationTimeInSecond})
	if err != nil {
		return err
	}
	return nil
}
